<template>
  <div class="upload-box">
    <div class="avatar-uploader-box">
      <!-- 图片预览 -->
      <div class="video-preview" v-for="(item, index) in videoList" :key="index" @mouseleave="mouseleave" @mouseenter="mouseenter(index)">
        <video v-if="item.videoLink" :src="`${videoBaseUrl}${item.videoLink}`" @mouseover.stop="item.isShowPopup = true" class="avatar">
          您的浏览器不支持视频播放
        </video>
        <video v-else :src="item.url" @mouseover.stop="item.isShowPopup = true" class="avatar">
          您的浏览器不支持视频播放
        </video>
        <div
          class="avatar-uploader-popup"
          v-if="index == ind"
        >
          <el-icon @click="previewVideo(item)"><ZoomIn /></el-icon>
          <el-icon @click="deleteVideo(item)"><Delete /></el-icon>
        </div>
      </div>

      <!-- 方框样式 -->
      <el-upload
        action="#"
        :before-upload="beforeAvatarUpload"
        :http-request="uploadSectionFile"
        :show-file-list="false"
        :multiple="false"
        class="avatar-uploader"
        ref="avatarUploader"
        v-loading="loading"
        v-if="uploadShow"
      >
        <span
          element-loading-background="rgba(0, 0, 0, 0.8)"
          element-loading-spinner="el-icon-loading"
          element-loading-text="上传中"
          style="display:block;"
          v-if="!loading"
        >
        <el-icon><Plus /></el-icon>
        </span>
      </el-upload>

      <!-- 上传提示文字样式 -->
      <div class="upload-tip">
        <slot></slot>
      </div>
    </div>

    <!-- 查看大图 -->
    <el-dialog v-model="videoDialog" append-to-body title="视频预览" :before-close="handleClose">
      <video :src="videoSrc" ref="video" id="videodom" controls alt style="width: 100%;height: 500px">您的浏览器不支持视频播放</video>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import useCurrentInstance from '@/utils/useCurrentInstance';
import OSS from 'ali-oss';

const emit = defineEmits(['upload-success', 'delete'])
const { proxy } = useCurrentInstance()
let ind = ref(-1)
const props = defineProps({
  videos: {
      type: Array,
      default: function() {
        return []
      }
    },
    numLimit: {
      // 最大允许上传个数
      type: Number,
      default: 1
    },
    sizeLimit: {
      // 最大单文件大小
      type: Number,
      default: 50
    },
    videoBaseUrl: {
      // 已上传图片服务器路径
      type: String,
      required: true
    }
})
let loading = ref(false)
let videoDialog = ref(false)
let videoList = ref([]) as any
let videoSrc = ref('')
let client = ref() as  any
let config = reactive({
  aliyunServerURL:'',
  accessid:'',
  AccessKeySecret:'',
  expiration:'',
  SecurityToken:'',
  policyBase64:'',
  signature:''
})

let uploadShow = ref(true) as any
watch(
  ()=>[props.videos],
  ()=>{
    const isArray = Array.isArray(props.videos)
    uploadShow.value = props.videos.length < props.numLimit
    if (isArray && props.videos.length > 0) {
      props.videos.map(item => {
        item.isShowPopup = false
      })
      videoList.value = JSON.parse(JSON.stringify(props.videos))
    } else {
      videoList.value = []
    }
  },
  {
    deep:true,
    immediate:true
  }
)
const beforeAvatarUpload = (file) => {
    let isVideo = true, isfileSize = true, isvideoLise = true
    if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
      proxy.$message.error("请上传正确的视频格式!");
      isVideo = false
    }else{
      isVideo = true
    }

    if (file.size / 1024 / 1024 > props.sizeLimit) {
      proxy.$message.error(`视频大小不能超过${props.sizeLimit}M!`);
      isfileSize = false
    }else{
      isfileSize = true
    }

    if (videoList.value.length === props.numLimit) {
      proxy.$message.error(`最多上传${props.numLimit}个视频`);
      isvideoLise = false
    }else{
      isvideoLise = true
    }
    return isVideo && isfileSize && isvideoLise
}
//上传进度
const progress = (p, checkpoint) => {
  if(Math.floor(p* 100) == 100){
    loading.value = false
    uploadShow.value = false
  }
}
const uploadSectionFile = (option) => {
  loading.value = true
  let file = option.file
  proxy.$api.uploadFile({file_type:'file'}).then(res => {
    // 定义上传文件的名字+后缀
    const aliyunilFeKey = res.result.token.Path + new Date().getTime() + Math.floor(Math.random() * 150) +'.'+file.name.split('.')[1]
    config.aliyunServerURL=`https://${res.result.token.Bucket}.${res.result.token.Region}.aliyuncs.com/`
    client.value = new OSS({
        accessKeyId: res.result.token.AccessKeyId,
        accessKeySecret: res.result.token.AccessKeySecret,
        stsToken: res.result.token.SecurityToken,
        region: res.result.token.Region,
        bucket: res.result.token.Bucket,
        secure:true
    })
    // 调用oss上传接口
    client.value.multipartUpload(aliyunilFeKey, file, {progress}).then(response=>{
      if (response.res.status === 200) {
          proxy.$message({
            type:'success',
            message:'上传成功'
          })
          videoSrc.value = config.aliyunServerURL+aliyunilFeKey
          videoList.value = [{url: videoSrc.value, name:new Date().getTime() + Math.floor(Math.random() * 150) +'.'+file.name.split('.')[1]}]
          emit('upload-success',config.aliyunServerURL+aliyunilFeKey)
      }else{
        proxy.$message({
          type:'error',
          message:'上传失败'
        })
        loading.value = false
      }
    }).catch(function (err) { console.error('error: ', err) })
  })
}

const mouseleave = () => {
  ind.value = -1
}
const mouseenter = (index) => {
  ind.value = index
}
// 预览视频
const previewVideo = (data) => {
  if (data.videoLink) {
    videoSrc.value = `${props.videoBaseUrl}${data.videoLink}`
  } else {
    videoSrc.value = data.url
  }
  videoDialog.value = true
}
// 删除视频
const deleteVideo = (index) => {
  videoList.value.splice(index, 1)
  videoSrc.value = ''
  emit('upload-success','')
  uploadShow.value = true
}
const handleClose = () => {
  const video = document.getElementsByTagName('video')[1]
  console.log(document.getElementById('videodom').currentTime)
  video.addEventListener(
      "timeupdate",
       () => {
        var timeDisplay;
        var duration;
        //用秒数来显示当前播放进度
        timeDisplay = Math.floor(video.currentTime);
        duration = Math.floor(video.duration);
        console.log("总时长", duration);
        console.log("当前播放的时长", timeDisplay);
      },
      false
  );
  if (!video.paused) {
    video.currentTime = 0
    video.pause()
  }
  videoDialog.value = false
}
</script>
<style lang="scss">
$width: 90px;
$height: 90px;

.upload-box {
  .avatar-uploader-box {
    position: relative;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    padding-bottom: 20px;
    min-width: 350px;
    .avatar-uploader {
      .el-upload {
        width: $width;
        height: $height;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: #409eff;
        }
        .el-loading-spinner {
          width: $width;
          height: $height;
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-top: 0;
          top: 0;
          .el-loading-text {
            margin: 0;
          }
        }
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: $width;
        height: $height;
        line-height: $height;
        text-align: center;
      }
    }
    .video-preview {
      position: relative;
      padding-right: 20px;
      .avatar {
        width: $width;
        height: $height;
        display: block;
        border-radius: 6px;
      }
      .avatar-uploader-popup {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: $width;
        height: $height;
        background: rgba($color: #000000, $alpha: 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        font-size: 20px;
        border-radius: 6px;
        i {
          width: 30%;
          text-align: center;
          padding: 0 5%;
          font-size: 24px;
        }
      }
    }
    .upload-tip {
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 12px;
      color: #606266;
      max-width: 350px;
      line-height: 20px;
    }
  }
}
</style>
